/**
*  Javascript sprintf
*  http://www.webtoolkit.info/
**/
sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%'; }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length);
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
};
 
sprintf = sprintfWrapper.init;

/**
 * DWT UI 
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.startsWith = function(str) {
	return (this.match("^" + str) == str);
};

String.prototype.endsWith = function(str) {
	return (this.match(str + "$") == str);
};

String.prototype.replaceAll = function(pcFrom, pcTo) {
	var i = this.indexOf(pcFrom);
	var c = this;

	while (i > -1) {
		c = c.replace(pcFrom, pcTo);
		i = c.indexOf(pcFrom);
	}
	return c;
};

String.prototype.toCamelCase = function() { 
	var s = this;
	var words = s.split(" ");
	var text = "";
	for (var i = 0; i < words.length; i++) {
		if (i > 0)
			text += " ";
		text += words[i].substring(0,1).toUpperCase() + words[i].substring(1).toLowerCase();
	}
	return text;
};

var DWT = {
		post : function(url, args, result) {
			var base = $("#base").attr("value");
			
			$.ajax({
				type:"post",
				url:base + url,
				data:args,
				success:result
			});
		},
		
		form : {
			clearFields : function() {
				$(":text").each(function(){
					$(this).attr("value", "");
				});
				$("select").each(function(){
					$(this).val($(this).find("option:first").val());
				});
			}
		},
		
		redirect : function(url) {
			var container = $(".container");
			
			$.get(url, function(data) {
				$(".container .frame").remove();
				container.append(data);
				
				transformLinks();
			});
		},
		
		loadComboBox : function(selector, list, label, value) {
			var options = '';
			for (var i = 0; i < list.length; i++) {
				options += '<option value="' + list[i][value] + '">' + list[i][label] + '</option>';
			}
			$(selector).html(options);
		},
		
		slideshow : {
			next : function(slideshow, data) {
				DWT.slideshow.move(slideshow, data, true);
			},

			prev : function(slideshow, data) {
				DWT.slideshow.move(slideshow, data, false);
			},
			
			move : function(slideshow, data, next) {
				var slide = slideshow.find("#slide");
				var value = parseInt(slide.attr("value"));

				if (next) {
					value = value + 1;
				} else {
					value = value - 1;
				}
				DWT.slideshow.display(slideshow, value, data);
			},
			
			display : function(slideshow, value, data) {
				var image = slideshow.find(".image");
				var subtitle = slideshow.find(".subtitle");
				var slide = slideshow.find("#slide");
				
				if (value < 0) {
					value = 0;
				} else if (value >= data.length) {
					value = data.length - 1;
				}
				slide.attr("value", value);
				
				image.attr("src", data[value].img);
				subtitle.html(data[value].subtitle);
				
				DWT.slideshow.checkVisibility(slideshow, data);
			},

			checkVisibility : function(slideshow, data) {
				var slide = slideshow.find("#slide");
				var value = parseInt(slide.attr("value"));
				
				if (value == 0) {
					slideshow.find(".buttonLeft").hide();
				} else {
					slideshow.find(".buttonLeft").show();
				}
				if (value >= (data.length - 1)) {
					slideshow.find(".buttonRight").hide();
				} else {
					slideshow.find(".buttonRight").show();
				}
				if (data[value].subtitle && data[value].subtitle != "") {
					slideshow.find(".subtitle").show();
				} else {
					slideshow.find(".subtitle").hide();
				}
			}
		},
		
		i18n : function(name, key) {
			var msg = "";
			$.ajax({url:$("#base").val() + "/i18n/" + name + "/" + key,async:false,enctype:"application/x-www-form-urlencoded",success:function(data){
				msg = data;
			}});
			return msg;
		},
		
		showMessageBox : function() {
			if ($(".messagebox").hasClass("info")) {
				$("#success ul").empty();
				$("#success ul").append($(".messagebox").html());
				$("#success").css("left", (($(window).width() - $("#success").outerWidth()) / 2) + $(window).scrollLeft() + "px");
				$("#success").slideDown();
			} else {
				$("#messagePopup .content").empty();
				$("#messagePopup .content").append($(".messagebox").html());
				DWT.openPopup("#messagePopup");
			}
		},
		
		addMessage : function(messageType, message) {
			$(".messagebox").addClass(messageType);
			$(".messagebox").append("<li>" + message + "</li>");
			DWT.showMessageBox();
		},
		
		removeAllMessages : function() {
			$(".messagebox li").remove();
			$(".messagebox").removeClass($(".messagebox").attr("class")).addClass("messagebox");
		},
		
		historyBack : function() {
			var i = $("#breadcrumb li").length - 1;
			if (i > -1) {
				var ref = $("#breadcrumb li:nth-child(" + i + ") a").attr("href");
				location.href = ref;
			}
		},
		
		openPopup : function(selector) {
			var glasspane = $("#glasspane");
			var popup = $(selector);

			glasspane.width($(window).width());
			glasspane.height($(document).height());

			glasspane.show();

			var left = (($(window).width() - popup.width()) / 2)
					+ $(window).scrollLeft();
			if (left < 0)
				left = 0;
			var top = (($(window).height() - popup.height()) / 2)
					+ $(window).scrollTop();
			if (top < 0)
				top = 0;

			popup.css({
				top : top + "px",
				left : left + "px"
			});

			popup.show();
		},

		closePopup : function(selector) {
			$(selector).hide();
			
			if ($(".popup:visible").length == 0)
				$("#glasspane").hide();
			
			if($("#scrollAcoes").length > 0) {
				$('html, body').animate({
					scrollTop: $("#scrollAcoes").offset().top
				}, 0);
			}
			
		},

		forceReload : function() {
			var autoId = 0;
			
			$(".autoreload").each(function(){
				var div = $(this);
				if (div.attr("id") == undefined || div.attr("id") == "")
					div.attr("id", "auto" + (++autoId));
				
				var url = div.attr("url");
				div.empty();
				$.ajax({url:url,type:"get",dataType:"html",async:false,success:function(data){
					div.append(data);
					
					reload("#" + div.attr("id") + " ");
				}});
			});
			
			try {
				otherReloads();
			} catch (e) {
				
			}
		}
		
};

$(function(){
	var date = new Date();
	var currentMonth = date.getMonth();
	var currentDate = date.getDate();
	var currentYear = date.getFullYear();
	var today = new Date(currentYear, currentMonth, currentDate);
	
	$(".messagebox").ajaxError(function(e, xhr, settings){
		if (xhr.status == 500) {
			$(".messagebox").addClass("error");
			$(".messagebox").append(xhr.responseText);
			DWT.showMessageBox();
		}
	});

	$(".datepicker").datepicker({
		onSelect: function ()
	    {
			 $(this).focus();
	    },
	
	    onClose: function ()
	    {
	    	 $(this).focus();
    	}
	});

	$(".datepicker-now").datepicker({
		maxDate : today
	});
	
	$(".menubar li, .embedmenubar li").click(function(){
		$(this).parent().find("li").each(function(){
			$(this).removeClass("selected");
		});
		$(this).addClass("selected");
	});
	
	$(".camelcase").keyup(function(event){
		if (event.keyChar == 32)
			return true;
		
		var text = $(this).attr("value");
		$(this).attr("value", text.toCamelCase());
	});

	$(".camelcase").blur(function(event){
		var text = $(this).attr("value");
		$(this).attr("value", text.toCamelCase());
	});
	
	$(".integer").unbind("keydown").keydown(function(event){
		if (event.keyCode == 8 
				|| event.keyCode == 9 
				|| event.keyCode == 13 
				|| event.keyCode == 16 
				|| event.keyCode == 17) {
			return true;
		}
		if (event.keyCode < 48 || event.keyCode > 57) {
			return false;
		}
	});
	
	$(".float").unbind("keypress").keypress(function(event) {
		if ((event.which > 47 && event.which < 58) || event.which == 0
				|| event.which == 8 || event.which == 9
				|| event.which == 13 || event.which == 16
				|| event.which == 17 || event.which == 44)
			return true;
		else
			return false;
	});
	
	$("#language li img").click(function(){
		var lang = $(this).attr("id");
		var url = $("#url").attr("value");
		document.location.href = "/language?lang=" + lang + "&url=" + url; 
	});
	
	$("button.clear").unbind("click").click(function(){
		DWT.form.clearFields();
		return false;
	});
	
	$(".autocomplete").each(function(){
		$(this).autocomplete($(this).attr("url"));
	});
	
	$(".popup").each(function() {
		var popup = $(this).detach();
		$("#popups").append(popup);
	});
	
	$(".slideshow").each(function(){
		var slideshow = $(this);
		var url = slideshow.attr("url");
		
		$.getJSON(url, function(data) {
			var image = slideshow.find(".image");
			var stretch = image.attr("stretch");
			var slide = slideshow.find("#slide");
			var value = parseInt(slide.attr("value"));
			
			if (stretch == "true") {
				image.attr("width", slideshow.css("width").replace("px", ""));
				image.attr("height", slideshow.css("height").replace("px", ""));
			}
			
			slideshow.next = function(evt){
				DWT.slideshow.next(slideshow, data);
			};

			slideshow.prev = function(){
				DWT.slideshow.prev(slideshow, data);
			};
			
			DWT.slideshow.display(slideshow, value, data);
			
			slideshow.mouseover(function(){
				DWT.slideshow.checkVisibility(slideshow, data);
			});
			slideshow.mouseleave(function(){
				$(this).find(".buttonLeft").hide();
				$(this).find(".buttonRight").hide();
				$(this).find(".subtitle").hide();
			});
			slideshow.mousewheel(function(e, delta){
				if (delta > 0)
					slideshow.prev();
				else
					slideshow.next();
				
				return false;
			});
			slideshow.find(".buttonLeft").click(function(){
				slideshow.prev();
			});
			slideshow.find(".buttonRight").click(function(){
				slideshow.next();
			});
		});
	});

	$("#loading").css(
			"left",
			(($(window).width() - $("#loading").outerWidth()) / 2)
					+ $(window).scrollLeft() + "px");

	$("#loading").ajaxStart(function() {
		$(this).show();
	});

	$("#loading").ajaxStop(function() {
		$(this).hide();
	});

	if ($(".messagebox li").length > 0) {
		DWT.showMessageBox();
	}
	
	transformLinks();
});

function transformLinks() {
	$(".readOnly").attr("readonly", true);
	
	$("#success img").unbind("click").click(function() {
		$("#success").slideUp();
	});
	
	$(".changeAction").unbind("click").click(function() {
		var form = $(this).parents("form");
		form.attr("action", $(this).attr("actionUrl"));
	});
	
	$(".creview li").click(function() {
		var value = parseInt($(this).attr("id"));
		
		var name = $(this).parent().attr("id").replace("_creview", "").replace(".", "\\.").trim();
		$("#" + name).attr("value", value);
		
		$(this).parent().children().each(function(){
			var id = parseInt($(this).attr("id"));
			
			if (id <= value) {
				$(this).addClass("review-checked");
			} else {
				$(this).removeClass("review-checked");
			}
		});
	});
	
	$(".delete").not(".ajax").click(function(e) {
		var msg = DWT.i18n("application", "message.confirm.delete");
		return confirm(msg);
	});
	
	$("a.ajax").each(function(){
		var href = $(this).attr("href");
		if (href != null && href.match("javascript.+") == null) {
			$(this).attr("href", "javascript:DWT.redirect('" + href + "');");
		} 
	});
	
	$("form.ajax").unbind("submit").submit(function(){
		var form = $(this);
		var url = form.attr("action");
		var params = {};
		$.each(form.serializeArray(), function(index, value) {
			params[value.name] = value.value;
		});

		var enctype = form.attr("enctype");
		if (enctype == null)
			enctype = "application/x-www-form-urlencoded";
		
		var remoteContent = form.find(".remoteContent");

		DWT.removeAllMessages();
		var msg = DWT.i18n("messages", "message.required.field");
		var submit = true;
		
		$(this).find(".required:text").each(function() {
			var field = $(this);
			if (field.attr("value").trim() == "") {
				var msgText = msg.replace("%s", field.prev("label").text().replace("*", "").replace(":", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});

		$(this).find("select.required").each(function() {
			var field = $(this);
			if (field.attr("value").trim() == "") {
				var msgText = msg.replace("%s", field.prev("label").text().replace("*", "").replace(":", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});
		
		$(this).find(".radio-boolean-required").each(function() {
			var length = $(this).find("input[type='radio']:checked").length;
			if (length == 0) {
				var msgText = msg.replace("%s", $(this).find("label").text().replace("*", "").replace("?", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});
		
		if (!submit)
			return false;
		
		$.ajax({
			url : url,
			type : "post",
			data : params,
			dataType : "html",
			contentType : enctype,
			success : function(data) {
				if (form.hasClass("forceReload")) {
					DWT.forceReload();
				} else {
					remoteContent.empty();
					remoteContent.append(data);

					reload("#" + remoteContent.attr("id") + " ");
				}
				
				var popup = form.parent(".popup");
				if (popup != undefined) {
					var popId = popup.attr("id");
					DWT.closePopup("#" + popId);
				}
				
				form.find("input").not("input[type=submit]").not("input[type=radio]").not("input[type=checkbox]").not("input[type=hidden]").not("input[type=button]").val(null);
				form.find("textarea").val(null).change();
			},
			error : function(jqXHR, textStatus, errorThrown) {
				$(".messagebox").empty();
			}
		});
		
		return false;
	});
	
	$("form").not(".ajax").unbind("submit").submit(function(){
		DWT.removeAllMessages();
		var msg = DWT.i18n("messages", "message.required.field");
		var submit = true;
		$(this).find(".required:text").each(function() {
			var field = $(this);
			if (field.attr("value").trim() == "") {
				var msgText = msg.replace("%s", field.prev("label").text().replace("*", "").replace(":", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});

		$(this).find("select.required").each(function() {
			var field = $(this);
			if (field.attr("value").trim() == "") {
				var msgText = msg.replace("%s", field.prev("label").text().replace("*", "").replace(":", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});
		
		$(this).find(".radio-boolean-required").each(function() {
			var length = $(this).find("input[type='radio']:checked").length;
			if (length == 0) {
				var msgText = msg.replace("%s", $(this).find("label").text().replace("*", "").replace("?", ""));
				DWT.addMessage("WARN", msgText);
				submit = false;
			}
		});
		
		return submit;
	});
	
	$(".openPopup").click(function() {
		var id = $(this).attr("popup");
		DWT.openPopup("#" + id);
		return false;
	});

	$(".closePopup").click(function() {
		var popup = $(this).parents(".popup");
		DWT.closePopup("#" + popup.attr("id"));
	});

}